package main;
import org.jgap.Chromosome;
import org.jgap.FitnessFunction;
import org.jgap.Gene;
import org.jgap.IChromosome;

public class SudokuFitness extends FitnessFunction {

	@Override
	protected double evaluate(IChromosome a_chromosome) {
	Gene gen_subjet = null;
	double fitness = 0; //Max 1296 son 81 elementos como mucho cada uno puede sumar 16 entonces 81*16
//	Chromosome clone_chromosome = (Chromosome) a_chromosome.clone();
//	Gene [] gens = clone_chromosome.getGenes();
	Gene [] gens = a_chromosome.getGenes();
	
	Gene[][] gens_matrix = fillGeneMatrix(gens);
	
	for(int i = 0; i < 9 ; i++){
		for(int j = 0; j < 9;j++){
			gen_subjet = gens_matrix[i][j];
			for(int repFila=0; repFila < 9; repFila++){
				if(gen_subjet!=gens_matrix[i][repFila]){
					if(!gen_subjet.getAllele().equals(gens_matrix[i][repFila].getAllele()))
						fitness++;					
				}
			}
			for(int repCol=0;repCol < 9;repCol++){
				if(gen_subjet!=gens_matrix[repCol][j]){
					if(!gen_subjet.getAllele().equals(gens_matrix[repCol][j].getAllele()))
						fitness++;					
				}
			}
		}
	}
		
	return fitness;
	}

	public Gene[][] fillGeneMatrix(Gene[] gens) {
		Gene[][] gens_matrix = new Gene[9][9];
		int totalGens = 0;	
		for(int i = 0; i < 9; i++){				
			for(int j = 0;j < 9; j++){
					gens_matrix[i][j] = gens[j+totalGens];
			}
			totalGens += 9;
		}
		return gens_matrix;
	}

}
